<!DOCTYPE html>
<html>
  <head>
    <title>Test Layout</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="https://www.google.com/jsapi?key=ABQIAAAAzdEw5E_SCg1w1KBcHq3rrxRaMymnJ2lvA8q0BRyPVizcDSlyCRReTTi1s3qfaqYdTqvLOr_EYx95Xg" type="text/javascript"></script>
    <link rel="stylesheet" media="screen" type="text/css" href="/css/grid.css" />
    <script language="Javascript" type="text/javascript">

    var gridRows = 3;
    var gridCols = 10;

    //<![CDATA[
    google.load("jquery", "1.4.2");
    google.load("jqueryui", "1.7.2");
    google.setOnLoadCallback(function() {
        var container = document.getElementById('box_container');
        //var container = document.body;

        // Grid Hover
        $('#grid li').hover(
        function(){
            var idbox = document.createElement("span");
            idbox.innerHTML = this.id;
            this.appendChild(idbox);
        },
        function(){
            $(this).empty();
        }
        );

        // Add Box
        $('#new_box').click(function(e){
            e.preventDefault();

            var box = document.createElement("div");
            box.id = "contentbox" + $('.contentbox').length;
            box.innerHTML = '&nbsp;';
            $(box).addClass("contentbox");
            container.appendChild(box);

            var grid = getNextGrid();
            console.log(grid);

            putBoxInGrid(box, grid);

        });

    });

    function getNextGrid(){
        var gridNode;
        loop:
        // Iterate Columns 2nd
        for (var x=0; x < gridCols; x++){
            // Iterate Rows first (Down First)
            for (var y=0; y < gridRows; y++){
                var gridNum = (y * 10) + x;
                if ($('.grid' + gridNum).length == 0){
                    gridNode = document.getElementById('grid'+gridNum);
                    break loop;
                }
            }
        }
        // If we got this far, the grid is full
        return (gridNode) ? gridNode : false;
    }


    function putBoxInGrid(box, grid){
        box.style.top = grid.offsetTop + 'px';
        box.style.left = grid.offsetLeft + 'px';
        // Replace grid from className list
        if( $(box).hasClass('grid*')){
                $(box).removeClass('grid*');

        }
        $(box).addClass(grid.id);
        $(box).draggable({
            revert: 'invalid',
            revertDuration: '100',
            stop: function(event, ui){
                console.log(event);
                console.log(ui);
            }
        });
    }

    function OnMouseDown(e)
    {
        // IE is retarded and doesn't pass the event object
        if (e == null)
            e = window.event;

        // IE uses srcElement, others use target
        var target = e.target != null ? e.target : e.srcElement;

        _debug.innerHTML = target.className == 'drag'
            ? 'draggable element clicked'
            : 'NON-draggable element clicked';

        // for IE, left click == 1
        // for Firefox, left click == 0
        if ((e.button == 1 && window.event != null ||
            e.button == 0) &&
            target.className == 'drag')
        {
            // grab the mouse position
            _startX = e.clientX;
            _startY = e.clientY;

            // grab the clicked element's position
            _offsetX = ExtractNumber(target.style.left);
            _offsetY = ExtractNumber(target.style.top);

            // bring the clicked element to the front while it is being dragged
            _oldZIndex = target.style.zIndex;
            target.style.zIndex = 10000;

            // we need to access the element in OnMouseMove
            _dragElement = target;

            // tell our code to start moving the element with the mouse
            document.onmousemove = OnMouseMove;

            // cancel out any text selections
            document.body.focus();

            // prevent text selection in IE
            document.onselectstart = function () { return false; };
            // prevent IE from trying to drag an image
            target.ondragstart = function() { return false; };

            // prevent text selection (except IE)
            return false;
        }
    }

    function OnMouseMove(e)
    {
        if (e == null)
            var e = window.event;

        // this is the actual "drag code"
        _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
        _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';

        _debug.innerHTML = '(' + _dragElement.style.left + ', ' +
            _dragElement.style.top + ')';
    }

    function OnMouseUp(e)
    {
        if (_dragElement != null)
        {
            _dragElement.style.zIndex = _oldZIndex;

            // we're done with these events until the next OnMouseDown
            document.onmousemove = null;
            document.onselectstart = null;
            _dragElement.ondragstart = null;

            // this is how we know we're not dragging
            _dragElement = null;

            _debug.innerHTML = 'mouse up';
        }
    }


    function ExtractNumber(value)
    {
        var n = parseInt(value);

        return n == null || isNaN(n) ? 0 : n;
    }

    //]]>
    </script>
  </head>
  <body>
      <a id="new_box" href="#">New Box</a>
      <div id="box_container"></div>
      <ul id="grid">
          <li id="grid0"></li>
          <li id="grid1"></li>
          <li id="grid2"></li>
          <li id="grid3"></li>
          <li id="grid4"></li>
          <li id="grid5"></li>
          <li id="grid6"></li>
          <li id="grid7"></li>
          <li id="grid8"></li>
          <li id="grid9"></li>
          <li id="grid10"></li>
          <li id="grid11"></li>
          <li id="grid12"></li>
          <li id="grid13"></li>
          <li id="grid14"></li>
          <li id="grid15"></li>
          <li id="grid16"></li>
          <li id="grid17"></li>
          <li id="grid18"></li>
          <li id="grid19"></li>
          <li id="grid20"></li>
          <li id="grid21"></li>
          <li id="grid22"></li>
          <li id="grid23"></li>
          <li id="grid24"></li>
          <li id="grid25"></li>
          <li id="grid26"></li>
          <li id="grid27"></li>
          <li id="grid28"></li>
          <li id="grid29"></li>
      </ul>
  </body>
</html>
